<template>
  <div class="user-profile-page">
    <!-- 顶部标题 -->
     <el-page-header
  content="用户画像"
  class="page-header"
  @back="goBack"
/>

    <el-row :gutter="20" class="profile-overview">
      <!-- 左侧：用户基本信息 -->
      <el-col :span="6">
        <el-card shadow="hover" class="profile-card">
          <div slot="header" class="clearfix">
            <span class="header-title">用户基本信息</span>
          </div>
          <div v-if="userInfo">
            <el-avatar
              :src="userInfo ? getAvatarUrl(userInfo.avatar) : defaultAvatar"
              size="large"
              class="avatar"
            />
            <el-descriptions
              :column="1"
              border
              class="user-descriptions"
            >
              <el-descriptions-item label="用户名">
                {{ userInfo.username }}
              </el-descriptions-item>
              <el-descriptions-item label="真实姓名">
                {{ userInfo.realName || '—' }}
              </el-descriptions-item>
              <el-descriptions-item label="邮箱">
                {{ userInfo.email }}
              </el-descriptions-item>
              <el-descriptions-item label="手机号">
                {{ userInfo.phone || '—' }}
              </el-descriptions-item>
              <el-descriptions-item label="性别">
                {{ genderLabel(userInfo.gender) }}
              </el-descriptions-item>
  
              <el-descriptions-item label="最后登录">
                {{ formatDate(userInfo.lastLogin) }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <div v-else class="loading-wrapper">
            <el-skeleton :rows="5" animated />
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：概览指标 -->
      <el-col :span="18">
        <el-row :gutter="20">
          <!-- 考试总数 / 正确率 / 最近一次成绩 等等 -->
          <el-col :span="6" v-for="stat in overviewStats" :key="stat.label">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-label">{{ stat.label }}</div>
              <div class="stat-value">{{ stat.value }}</div>
            </el-card>
          </el-col>
        </el-row>

         <!-- 新增：可视化图表区域（红色框部分） -->
        <el-row :gutter="20" class="charts-area" style="margin-top: 20px;">
          <!-- 活跃度折线图 -->
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <div slot="header" class="clearfix">
                <span>最近一周活跃度</span>
              </div>
              <!-- 修改图表容器 -->
              <div class="chart-wrapper">
                <v-chart
                  class="echarts-container"
                  :option  ="activityChartOptions "
                  :autoresize="true"
                  :loading="!activityChartOptions"
                />
              </div>
            </el-card>
          </el-col>

          <!-- 题型正确率分布饼图 -->
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <div slot="header" class="clearfix">
                <span>题型正确率分布</span>
              </div>
              <!-- 修改图表容器 -->
              <div class="chart-wrapper">
                <v-chart
                  class="echarts-container"
                  :option =" typePieChartOptions "
                  :autoresize="true"
                  :loading="!typePieChartOptions"
                />
                <!-- 
总结：
这段代码的作用是渲染一个自动适应大小的 ECharts 饼图，并在数据未加载时显示加载动画。你可以根据 typePieChartOptions 的内容来控制图表的显示和加载状态。

！ -->
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <el-divider />

    <!-- 中部：Tab 切换各大模块 -->
    <el-tabs v-model="activeTab" type="card" class="profile-tabs" @tab-click="onTabChange">
      <!-- 最近考试记录 -->
      <el-tab-pane label="最近考试记录" name="exams">
        <div v-if="examRecords">
          <el-table
            :data="examRecords"
            stripe
            style="width: 100%"
          >
            <el-table-column
              prop="paperName"
              label="试卷名称"
              width="240"
            />
            <el-table-column
              prop="totalScore"
              label="试卷总分"
              width="100"
            />
            <el-table-column
              prop="userScore"
              label="得分"
              width="100"
            />
            <el-table-column
              prop="duration"
              label="时长（秒）"
              width="120"
            />
            <el-table-column
              prop="createTime"
              label="考试时间"
              width="180"
            >
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else class="loading-wrapper">
          <el-skeleton :rows="4" animated />
        </div>
      </el-tab-pane>

      <!-- 最近练习记录 -->
      <el-tab-pane label="最近练习记录" name="practices">
        <div v-if="practiceRecords">
          <el-table :data="practiceRecords" stripe style="width: 100%">
            <el-table-column prop="courseName" label="课程" width="180" />
            <el-table-column prop="questionCount" label="练习题数" width="120" />
            <el-table-column prop="correctCount" label="正确题数" width="120" />
            <el-table-column prop="duration" label="时长（秒）" width="120" />
            <el-table-column
              prop="createTime"
              label="练习时间"
              width="180"
            >
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else class="loading-wrapper">
          <el-skeleton :rows="4" animated />
        </div>
      </el-tab-pane>

      <!-- 收藏题目 -->
      <el-tab-pane label="收藏题目" name="favorites">
        <div v-if="favorites">
          <el-table :data="favorites" stripe style="width: 100%">
            <el-table-column prop="questionContent" label="题目内容" />
            <el-table-column
              prop="createTime"
              label="收藏时间"
              width="180"
            >
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else class="loading-wrapper">
          <el-skeleton :rows="4" animated />
        </div>
      </el-tab-pane>

      
      <!-- 答题表现（正确率/题型分布）-->
      <el-tab-pane label="答题表现" name="performance">
        <div class="performance-section">
          <el-card shadow="hover" class="performance-card">
            <div slot="header" class="clearfix">
              <span>总体答题正确率</span>
            </div>
            <el-progress
              :percentage="overallAccuracy"
              status="success"
              class="overall-progress"
            />
            <div class="accuracy-text">
              {{ overallAccuracy }}%
            </div>
          </el-card>

          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="12">
              <el-card shadow="hover" class="performance-card">
                <div slot="header" class="clearfix">
                  <span>学习趋势</span>
                </div>
                <v-chart
                class="echarts-container"
                :option="studyTrendChartOptions"
                :autoresize="true"
                :loading="!studyTrendChartOptions"
              />
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card shadow="hover" class="performance-card">
                <div slot="header" class="clearfix">
                  <span>题型正确率分布</span>
                </div>
               <v-chart
              class="echarts-container"
              :option="typeAccuracyChartOptions"
              :autoresize="true"
              :loading="!typeAccuracyChartOptions"
            />
            <!-- 但 ECharts 组件用的是 option。 -->
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>

      <!-- 薄弱知识点 -->
      <el-tab-pane label="薄弱知识点" name="weakPoints">
        <div>
          <el-table :data="weakPoints" stripe style="width: 100%">
           <el-table-column prop="pointName" label="知识点" width="200">
  <template #default="scope">
    {{ typeof scope.row.pointName === 'object'
        ? scope.row.pointName.pointName
        : scope.row.pointName }}
  </template>
</el-table-column>
            <el-table-column prop="totalAttempts" label="做题总数" width="120" />
            <el-table-column prop="correctCount" label="正确数" width="120" />
            <el-table-column prop="accuracy" label="正确率 (%)" width="120">
              <template #default="scope">
                {{ scope.row.accuracy.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import axios from "axios";
// 从 vue-echarts 中导入 ECharts Vue 组件
import { defineComponent } from 'vue';

import * as echarts from "echarts/core";
// 引入需要的图表类型
import {
  LineChart,
  PieChart
} from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
} from "echarts/components";
import {
  CanvasRenderer
} from "echarts/renderers";
// 最后注册
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  LineChart,
  PieChart,
  CanvasRenderer
]);
// 用 `vue-echarts` 提供的组件包装
import { use } from "echarts/core";
import VChart from "vue-echarts";

export default {
  name: "UserProfile",
  components: {
    "v-chart": VChart,
  },
  data() {
    return {
      // ── 用户、记录等原始数据 ──
      userInfo: null,
      examRecords: null,
      practiceRecords: null,
      favorites: null,
      studyPlans: null,
      weakPoints: [], // 添加薄弱知识点数据
      userAnalysis: null, // 添加用户分析数据

      // ── 可视化图表相关 ──
      oneWeekActivity: [],      // [{ date: '2025-06-01', count: 5 }, …]
      activityChartOptions: {}, // ECharts 折线图配置项

      typeAccuracyList: [],     // [{ name: '数学-选择', value: 75 }, …]
      typePieChartOptions: [],  // ECharts 饼图配置项

      // ── 其他展示逻辑用到的字段 ──
      activeTab: "exams",
      overallAccuracy: 0,
      defaultAvatar: "/images/default-avatar.png",
      avatarBasePath: "/avatars/", 
      supportedImageFormats: ['.jpg', '.jpeg', '.png', '.gif'], // 支持的图片格式
      studyTrendChartOptions: {}, // 学习趋势图表配置
      typeAccuracyChartOptions: {}, // 题型正确率分布图配置
    };
  },
  computed: {
    overviewStats() {
      return [
        {
          label: "总考试次数",
          value: this.examRecords ? this.examRecords.length : 0,
        },
        {
          label: "总练习次数",
          value: this.practiceRecords ? this.practiceRecords.length : 0,
        },
        {
          label: "收藏题目数",
          value: this.favorites ? this.favorites.length : 0,
        },
        {
          label: "进行中计划数",
          value: this.studyPlans
            ? this.studyPlans.filter((p) => p.status === 1).length
            : 0,
        },
      ];
    },
  },
  methods: {
    goBack() {
    // 返回上一页（浏览器历史记录）
    this.$router ? this.$router.back() : window.history.back();
  },
    getUserId() {
      return Number(this.$route.params.userId || 0);
    },
    formatDate(dateStr) {
      if (!dateStr) return "—";
      try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return "—";
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return "—";
      }
    },
    genderLabel(code) {
      switch (code) {
        case 1:
          return "男";
        case 2:
          return "女";
        default:
          return "未知";
      }
    },
    planStatusLabel(status) {
      switch (status) {
        case 0:
          return "未开始";
        case 1:
          return "进行中";
        case 2:
          return "已完成";
        case 3:
          return "已放弃";
        default:
          return "未知";
      }
    },
    planStatusTagType(status) {
      switch (status) {
        case 0:
          return "info";
        case 1:
          return "warning";
        case 2:
          return "success";
        case 3:
          return "danger";
        default:
          return "default";
      }
    },

    // 处理头像路径
    getAvatarUrl(avatar) {
      try {
        console.log('原始头像路径:', avatar);
        
        if (!avatar) {
          console.log('头像为空，使用默认头像');
          return this.defaultAvatar;
        }
        
        // 如果头像路径是完整的URL，直接返回
        if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
          console.log('检测到网络头像URL:', avatar);
          return avatar;
        }
        
        // 如果是本地头像，使用相对路径
        // 移除开头的斜杠，避免重复
        const cleanAvatar = avatar.startsWith('/') ? avatar.substring(1) : avatar;
        
        // 检查文件格式
        const hasValidExtension = this.supportedImageFormats.some(format => 
          cleanAvatar.toLowerCase().endsWith(format)
        );
        
        // 如果路径已经包含 avatars 目录
        if (cleanAvatar.startsWith('avatars/')) {
          const fullPath = `/${cleanAvatar}`;
          console.log('处理后的头像路径:', fullPath);
          return fullPath;
        }
        
        // 如果没有有效的文件扩展名，添加默认扩展名
        const avatarWithExtension = hasValidExtension ? cleanAvatar : `${cleanAvatar}.jpg`;
        const fullPath = `${this.avatarBasePath}${avatarWithExtension}`;
        console.log('处理后的头像路径:', fullPath);
        return fullPath;
      } catch (error) {
        console.error('处理头像路径时出错:', error);
        return this.defaultAvatar;
      }
    },

    // 修改获取用户基本信息方法
    async fetchUserInfo() {
      try {
        const uid = this.getUserId();
        console.log('开始获取用户信息，用户ID:', uid);
        
        const response = await axios.get(`http://localhost:8080/user/user_find/${uid}`);
        console.log('获取到用户信息:', response.data);
        
        if (!response.data) {
          console.warn('未获取到用户数据');
          throw new Error('未获取到用户数据');
        }

        this.userInfo = response.data;
        
        // 处理头像路径
        if (this.userInfo && this.userInfo.avatar) {
          console.log('处理前的头像路径:', this.userInfo.avatar);
          // 确保头像路径包含文件扩展名
          const avatarPath = this.userInfo.avatar.includes('.') 
            ? this.userInfo.avatar 
            : `${this.userInfo.avatar}.jpg`;
          this.userInfo.avatar = this.getAvatarUrl(avatarPath);
          console.log('处理后的头像路径:', this.userInfo.avatar);
        } else {
          console.log('用户没有设置头像');
          this.userInfo.avatar = this.defaultAvatar;
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        this.userInfo = {
          username: '未知用户',
          avatar: this.defaultAvatar
        };
      }
    },

    // 修改获取考试记录方法
async fetchExamRecords() {
  try {
    const uid = this.getUserId();
    console.log('开始获取考试记录，用户ID:', uid);

    // 使用原始考试记录接口
    const response = await axios.get(`http://localhost:8080/userexams/byUser/${uid}`);
    console.log('考试记录原始数据:', response.data);

    if (response.data && Array.isArray(response.data)) {
      const examList = response.data;

      // 并发处理每条考试记录
      const recordsWithRealNames = await Promise.all(
        examList.map(async (item) => {
          let { paperName, paperId } = item;

          // 判断是否是假名称（如“试卷一”）
          const isFakeName = !paperName || /^试卷[一二三四五六七八九十\d]+$/.test(paperName);

          // 若是假名称且存在 paperId，则去查真实试卷名称
          if (isFakeName && paperId) {
            try {
              // ✅ 正确接口：获取试卷详情
              const res = await axios.get(`http://localhost:8080/exam-papers/${paperId}`);
              console.log(`试卷ID ${paperId} 接口响应：`, res.data);

              // 提取真实名称字段
              paperName = res.data?.paperName || res.data?.name || res.data?.title || `试卷${paperId}`;
            } catch (err) {
              console.warn(`❗试卷ID ${paperId} 查询失败，将使用默认名称`, err);
              paperName = `试卷${paperId}`;
            }
          }

          console.log(`✅ 最终使用的试卷名称: ${paperName} （试卷ID: ${paperId}）`);

          return {
            paperName,
            totalScore: item.totalScore || 0,
            userScore: item.userScore || 0,
            duration: item.duration || 0,
            createTime: item.createTime || new Date().toISOString(),
            examId: item.examId,
            paperId: item.paperId,
          };
        })
      );

      this.examRecords = recordsWithRealNames;

      // 更新图表数据
      await this.computeOneWeekActivity();
    }
  } catch (error) {
    console.error("获取考试记录失败:", error);
    this.examRecords = [];
  }
}

,
    // 获取用户练习记录
   async fetchPracticeRecords() {
  try {
    const uid = this.getUserId();
    console.log('开始获取练习记录，用户ID:', uid);

    const response = await axios.get(`http://localhost:8080/userPractices/user/${uid}`);
    console.log('获取到练习原始数据:', response.data);

    if (!response.data || !Array.isArray(response.data)) {
      this.practiceRecords = [];
      return;
    }

    const practiceList = response.data;

    const recordsWithRealCourseName = await Promise.all(
      practiceList.map(async (item) => {
        let courseName = item.courseName;
        const courseId = item.courseId;

        // 判断是否是假名称（如课程1、课程二）
        const isFakeName = !courseName || /^课程[一二三四五六七八九十\d]+$/.test(courseName);

        if (isFakeName && courseId) {
          try {
            const res = await axios.get(`http://localhost:8080/Courses/findid?course_id=${courseId}`);
            console.log(`课程ID ${courseId} 接口响应：`, res.data);
            courseName = res.data?.courseName || res.data?.name || `课程${courseId}`;
          } catch (err) {
            console.warn(`❗课程ID ${courseId} 查询失败，使用默认名称`, err);
            courseName = `课程${courseId}`;
          }
        }

        return {
          courseName,
          questionCount: item.questionCount || 0,
          correctCount: item.correctCount || 0,
          duration: item.duration || 0,
          createTime: item.startTime || new Date().toISOString(),
          practiceId: item.practiceId,
          courseId: item.courseId,
          pointId: item.pointId
        };
      })
    );

    this.practiceRecords = recordsWithRealCourseName;

    // 重新计算图表（活跃度）
    await this.computeOneWeekActivity();
  } catch (error) {
    console.error("获取练习记录失败:", error);
    this.practiceRecords = [];
  }
},



    // 获取用户收藏题目
    async fetchFavorites() {
      try {
        const uid = this.getUserId();
        console.log('开始获取收藏题目，用户ID:', uid);
        // 使用新的接口，带 userId 参数
        const response = await axios.get(`http://localhost:8080/user_favorites_vo/listByUserId/${uid}`);
        console.log('获取到收藏题目原始数据:', response.data);
        this.favorites = response.data;
      } catch (error) {
        console.error("获取收藏题目失败:", error);
        this.favorites = [];
      }
    },

    // 获取用户学习计划
    async fetchStudyPlans() {
      try {
        const uid = this.getUserId();
        console.log('开始获取学习计划，用户ID:', uid);
        
        const response = await axios.get(`http://localhost:8080/userstudyplans/finduserall`, {
          params: { userid: uid },
        });
        console.log('获取到学习计划原始数据:', response.data);
        
        this.studyPlans = response.data.map((item) => {
          console.log('处理学习计划项:', item);
          
          // 处理日期格式
          const formatDate = (dateStr) => {
            if (!dateStr) return '';
            try {
              // 如果已经是 YYYY-MM-DD 格式，直接返回
              if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
                return dateStr;
              }
              const date = new Date(dateStr);
              if (isNaN(date.getTime())) return '';
              const year = date.getFullYear();
              const month = String(date.getMonth() + 1).padStart(2, '0');
              const day = String(date.getDate()).padStart(2, '0');
              return `${year}-${month}-${day}`;
            } catch (error) {
              console.error('日期格式化错误:', error);
              return '';
            }
          };

          return {
            planName: item.planName || `学习计划${item.planId || '新'}`,
            startDate: formatDate(item.startDate),
            endDate: formatDate(item.endDate),
            dailyTarget: parseInt(item.dailyTarget) || 0,
            currentProgress: parseInt(item.currentProgress) || 0,
            status: parseInt(item.status) || 0,
            id: item.planId,
            createTime: item.createTime,
            updateTime: item.updateTime
          };
        });
        console.log('处理后的学习计划数据:', this.studyPlans);
      } catch (error) {
        console.error("获取学习计划失败:", error);
        this.studyPlans = [];
      }
    },

    // 修改计算活跃度方法
    async computeOneWeekActivity() {
      try {
        console.log('开始计算活跃度...');
        const today = new Date();
        const dateList = [];
        
        // 生成最近7天的日期列表
        for (let i = 6; i >= 0; i--) {
          const d = new Date(today);
          d.setDate(today.getDate() - i);
          const yyyy = d.getFullYear();
          const mm = String(d.getMonth() + 1).padStart(2, "0");
          const dd = String(d.getDate()).padStart(2, "0");
          dateList.push(`${yyyy}-${mm}-${dd}`);
        }
        
        const activityMap = {};
        dateList.forEach((dt) => {
          activityMap[dt] = 0;
        });

        // 统计练习记录
        if (this.practiceRecords && this.practiceRecords.length > 0) {
          this.practiceRecords.forEach((rec) => {
            if (rec.createTime) {
              const date = new Date(rec.createTime).toISOString().split('T')[0];
              if (activityMap.hasOwnProperty(date)) {
                activityMap[date] += 1;
              }
            }
          });
        }

        // 统计考试记录
        if (this.examRecords && this.examRecords.length > 0) {
          this.examRecords.forEach((rec) => {
            if (rec.createTime) {
              const date = new Date(rec.createTime).toISOString().split('T')[0];
              if (activityMap.hasOwnProperty(date)) {
                activityMap[date] += 1;
              }
            }
          });
        }

        this.oneWeekActivity = dateList.map((dt) => ({
          date: dt,
          count: activityMap[dt],
        }));

        // 确保在数据更新后重新初始化图表
        await this.initActivityChartOptions();
        
      } catch (error) {
        console.error("计算活跃度失败:", error);
        this.oneWeekActivity = [];
      }
    },

    // 修改图表初始化方法
    initActivityChartOptions() {
      console.log('开始初始化活跃度图表...');
      console.log('当前活跃度数据:', this.oneWeekActivity);
      
      const dates = this.oneWeekActivity.map((item) => item.date);
      const counts = this.oneWeekActivity.map((item) => item.count);
      
      console.log('图表X轴数据:', dates);
      console.log('图表Y轴数据:', counts);

      this.activityChartOptions = {
        tooltip: {
          trigger: "axis",
          formatter: "{b0}: {c0} 次",
        },
        xAxis: {
          type: "category",
          data: dates,
          boundaryGap: false,
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: "value",
          minInterval: 1,
          axisLabel: {
            formatter: "{value} 次",
          },
        },
        series: [
          {
            name: "活跃度",
            type: "line",
            data: counts,
            smooth: true,
            lineStyle: { width: 3 },
            itemStyle: { color: "#409EFF" },
            areaStyle: { color: "rgba(64,158,255,0.2)" },
            symbol: 'circle',
            symbolSize: 8,
            emphasis: {
              focus: 'series'
            }
          },
        ],
        grid: {
          left: "3%",
          right: "4%",
          bottom: "15%",
          top: "10%",
          containLabel: true,
        },
        animation: true,
      };
      console.log('活跃度图表配置完成:', this.activityChartOptions);
    },

    // 修改计算题型正确率方法
    async computeTypeAccuracy() {
      try {
        console.log('开始计算题型正确率...');
        const uid = this.getUserId();
        console.log('用户ID:', uid);
        
        const response = await axios.get(`http://localhost:8080/useranalysis/findbyuserid`, {
          params: { userId: uid }
        });
        console.log('获取到的用户分析数据:', response.data);

        if (response.data && Array.isArray(response.data)) {
          // 合并所有分析记录中的题型数据
          const typeMap = new Map();
          
          response.data.forEach(analysis => {
            console.log('处理分析记录:', analysis);
            if (analysis.weakPoints) {
              try {
                const weakPointsObj = JSON.parse(analysis.weakPoints);
                console.log('解析后的薄弱知识点:', weakPointsObj);
                Object.entries(weakPointsObj).forEach(([chapter, point]) => {
                  if (!typeMap.has(point)) {
                    typeMap.set(point, {
                      name: point,
                      value: analysis.accuracyRate ? parseFloat(analysis.accuracyRate) : 0
                    });
                  }
                });
              } catch (error) {
                console.error('解析题型数据失败:', error);
              }
            }
          });

          this.typeAccuracyList = Array.from(typeMap.values()).map(item => ({
  ...item,
  name: typeof item.name === 'object' ? item.name.pointName : item.name
}));
          console.log('最终生成的题型正确率数据:', this.typeAccuracyList);
          
          // 确保在数据更新后重新初始化图表
          await this.initTypePieChartOptions();
        }
      } catch (error) {
        console.error("计算题型正确率失败:", error);
        this.typeAccuracyList = [];
      }
    },

    // 修改饼图初始化方法
    initTypePieChartOptions() {
      console.log('开始初始化题型正确率饼图...');
      console.log('当前题型正确率数据:', this.typeAccuracyList);

      // 如果没有数据，显示空状态
      if (!this.typeAccuracyList || this.typeAccuracyList.length === 0) {
        this.typePieChartOptions = {
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'center'
          }
        };
        return;
      }

      this.typePieChartOptions = {
        tooltip: {
          trigger: "item",
          formatter: "{b}:{c}%",
        },
        
        
        series: [
          {
            name: "题型正确率",
            type: "pie",
            radius: ["40%", "60%"],
            center: ["50%", "50%"], // 调整中心点位置
            label: {
              show: true,
              formatter: " {d}%",
              fontSize: 12,
              position: "outside"
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            data: this.typeAccuracyList.map(item => ({
              name: item.name,
              value: parseFloat(item.value) || 0
            }))
          },
        ],
      };
      console.log('题型正确率饼图配置完成:', this.typePieChartOptions);
    },

    // 修改 handleResize 方法
    handleResize() {
      console.log('处理窗口大小变化...');
      this.$nextTick(() => {
        if (this.activityChartOptions) {
          console.log('重新初始化活跃度图表');
          this.initActivityChartOptions();
        }
        if (this.typePieChartOptions) {
          console.log('重新初始化题型正确率饼图');
          this.initTypePieChartOptions();
        }
      });
    },

    // 初始化学习趋势图表
    initStudyTrendChart() {
      if (!this.userAnalysis || this.userAnalysis.length === 0) {
        this.studyTrendChartOptions = {
          title: {
            text: '暂无学习趋势数据',
            left: 'center'
          }
        };
        return;
      }

      // 合并所有分析记录中的学习趋势
      const trendMap = new Map();
      
      this.userAnalysis.forEach(analysis => {
        if (analysis.studyTrend) {
          try {
  const trendObj = JSON.parse(analysis.studyTrend);
  if (!trendObj || typeof trendObj !== 'object') {
    console.warn('studyTrend 格式不正确:', trendObj);
    return;
  }
  Object.entries(trendObj).forEach(([month, count]) => {
    if (!trendMap.has(month)) {
      trendMap.set(month, 0);
    }
    trendMap.set(month, trendMap.get(month) + count);
  });
} catch (error) {
  console.error('解析学习趋势数据失败:', error);
}

          
  

        }
      });

      // 转换为图表数据
      const months = Array.from(trendMap.keys()).sort();
      const counts = months.map(month => trendMap.get(month));

      this.studyTrendChartOptions = {
        title: {
          text: '学习趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c} 题'
        },
        xAxis: {
          type: 'category',
          data: months,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '题目数量'
        },
        series: [
          {
            name: '做题数量',
            type: 'line',
            data: counts,
            smooth: true,
            lineStyle: { width: 3 },
            itemStyle: { color: '#409EFF' },
            areaStyle: { color: 'rgba(64,158,255,0.2)' }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        }
      };
    },

    // 初始化题型正确率分布图
    initTypeAccuracyChart() {
      if (!this.userAnalysis || this.userAnalysis.length === 0) {
        this.typeAccuracyChartOptions = {
          title: {
            text: '暂无题型正确率数据',
            left: 'center'
          }
        };
        return;
      }

      // 合并所有分析记录中的题型数据
      const typeMap = new Map();
      
      this.userAnalysis.forEach(analysis => {
        if (analysis.weakPoints) {
          try {
            const weakPointsObj = JSON.parse(analysis.weakPoints);
            Object.entries(weakPointsObj).forEach(([chapter, point]) => {
              if (!typeMap.has(point)) {
                typeMap.set(point, {
                  name: point,
                  value: analysis.accuracyRate ? (analysis.accuracyRate * 1) : 0
                });
              }
            });
          } catch (error) {
            console.error('解析题型数据失败:', error);
          }
        }
      });

      // 转换为图表数据
      const typeData = Array.from(typeMap.values());

      this.typeAccuracyChartOptions = {
        title: {
          text: '题型正确率分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}%'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          top: 20
        },
        series: [
          {
            name: '题型正确率',
            type: 'pie',
            radius: ['40%', '60%'],
            center: ['50%', '55%'],
            label: {
              show: true,
              formatter: '{b}\n{d}%',
              fontSize: 12
            },
            data: typeData
          }
        ]
      };
    },

    // 修改 processWeakPoints 方法
    processWeakPoints() {
      if (!this.userAnalysis || this.userAnalysis.length === 0) {
        this.weakPoints = [];
        return;
      }

      // 合并所有分析记录中的薄弱知识点
      const weakPointsMap = new Map();
      
      this.userAnalysis.forEach(analysis => {
        if (analysis.weakPoints) {
          try {
            const weakPointsObj = JSON.parse(analysis.weakPoints);
            Object.entries(weakPointsObj).forEach(([chapter, point]) => {
              if (!weakPointsMap.has(point)) {
                weakPointsMap.set(point, {
                  pointName: point,
                  totalAttempts: analysis.totalQuestions || 0,
                  correctCount: analysis.correctQuestions || 0,
                  accuracy: analysis.accuracyRate ? (analysis.accuracyRate * 1) : 0
                });
              }
            });
          } catch (error) {
            console.error('解析薄弱知识点失败:', error);
          }
        }
      });

      // 计算每个知识点的正确率
      this.weakPoints = Array.from(weakPointsMap.values());
      console.log('最终 weakPoints:', this.weakPoints)
    },

    // 修改 fetchUserAnalysis 方法
   async fetchUserAnalysis() {
  try {
    const uid = this.getUserId();
    console.log('开始获取用户分析数据，用户ID:', uid);

    const response = await axios.get(`http://localhost:8080/useranalysis/findbyuserid`, {
      params: { userId: uid }
    });
    console.log('获取到用户分析数据:', response.data);

    if (response.data && Array.isArray(response.data)) {
      this.userAnalysis = response.data;

      // 要求每个分析记录都包含必要的字段
      // 批注：如果用户分析数据为空，通常是该用户还没有做过题或后台没有分析数据
      if (this.userAnalysis.length === 0) {
        console.warn('⚠️ 用户分析数据为空，请检查数据库是否有相关内容');
      }

      this.computeOverallAccuracy();
      this.processWeakPoints();
      this.initStudyTrendChart();
      this.initTypeAccuracyChart();
    } else {
      console.warn('用户分析数据格式不正确:', response.data);
      this.userAnalysis = [];
    }
  } catch (error) {
    console.error("获取用户分析数据失败:", error);
    this.userAnalysis = [];
  }
},
    // 计算总体正确率
    computeOverallAccuracy() {
      if (!this.userAnalysis || this.userAnalysis.length === 0) {
        this.overallAccuracy = 0;
        return;
      }

      let totalQuestions = 0;
      let totalCorrect = 0;

      this.userAnalysis.forEach(analysis => {
        totalQuestions += analysis.totalQuestions || 0;
        totalCorrect += analysis.correctQuestions || 0;
      });

      this.overallAccuracy = totalQuestions > 0 
        ? Math.round((totalCorrect / totalQuestions) * 100) 
        : 0;
    },
  },
  mounted() {
  console.log('组件开始挂载...');
  Promise.all([
    this.fetchUserInfo(),
    this.fetchExamRecords(),
    this.fetchPracticeRecords(),
    this.fetchFavorites(),
    this.fetchStudyPlans(),
    this.fetchUserAnalysis(),
    this.computeTypeAccuracy()
  ]).then(() => {
    this.$nextTick(() => {
      console.log('DOM 更新完成，开始初始化图表');
      this.initActivityChartOptions();

      // 添加这两句，确保两个图表正确初始化
      this.initStudyTrendChart();
      this.initTypeAccuracyChart();

      window.addEventListener('resize', this.handleResize);
      setTimeout(() => {
        window.dispatchEvent(new Event('resize'));
      }, 200);
    });
  }).catch(error => {
    console.error('数据加载失败:', error);
  });
},


   beforeUnmount() {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize);
  },
};
</script>
<style scoped>
.user-profile-page {
  padding: 24px;
  background-color: #f5f7fa;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  color: #333;
}

/* 顶部页头 */
.page-header {
  margin-bottom: 24px;
  font-size: 20px;
  font-weight: bold;
}

/* 卡片标题居中 */
.header-title {
  display: block;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 左右布局（默认桌面） */
.profile-overview {
  display: flex;
  align-items: stretch;
  flex-wrap: nowrap;
}

/* 左侧卡片 */
.profile-card {
  margin-bottom: 20px;
  height: 100%;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.avatar {
  display: block;
  margin: 0 auto 12px auto;
}
.user-descriptions {
  margin-top: 10px;
  font-size: 14px;
}
.loading-wrapper {
  padding: 20px;
}

/* 右侧概览指标 */
.stat-card {
  text-align: center;
  padding: 24px 0;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}
.stat-label {
  font-size: 14px;
  color: #909399;
}
.stat-value {
  font-size: 26px;
  font-weight: bold;
  margin-top: 6px;
  color: #409eff;
}

/* Tab 区域 */
.profile-tabs {
  margin-top: 24px;
}

/* 答题表现部分 */
.performance-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.performance-card {
  margin-bottom: 20px;
  border-radius: 12px;
}
.overall-progress {
  width: 100%;
  margin-top: 10px;
}
.accuracy-text {
  text-align: center;
  font-size: 20px;
  margin-top: 8px;
  font-weight: 500;
  color: #67c23a;
}

/* 图表区域 */
.charts-area {
  margin-top: 20px;
}
.chart-card {
  height: 400px;
  position: relative;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
.chart-wrapper {
  position: relative;
  width: 100%;
  height: 350px;
  padding: 16px;
}
.echarts-container {
  width: 100% !important;
  height: 100% !important;
  min-height: 300px;
}

/* ==================== 响应式布局 ==================== */

/* 平板设备（≤ 992px） */
@media (max-width: 992px) {
  .profile-overview {
    flex-wrap: wrap;
  }

  .profile-card {
    width: 100% !important;
    margin-bottom: 20px;
  }

  .stat-card {
    padding: 20px 0;
  }

  .chart-card {
    height: auto;
  }

  .chart-wrapper {
    height: 300px;
    padding: 12px;
  }
  /* 让 el-col 内容等高 */
.profile-overview :deep(.el-col) {
  display: flex;
  flex-direction: column;
}

/* 让卡片自适应填满 el-col */
.profile-card,
.charts-area {
  flex: 1;
}

}

/* 手机设备（≤ 600px） */
@media (max-width: 600px) {
  .page-header {
    font-size: 18px;
  }

  .header-title {
    font-size: 14px;
  }

  .stat-value {
    font-size: 20px;
  }

  .accuracy-text {
    font-size: 16px;
  }

  .echarts-container {
    min-height: 260px;
  }

  .chart-wrapper {
    height: 260px;
    padding: 10px;
  }
}
</style>
